package xim

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 创建人与人之间的聊天窗
//
//	uid	用户ID
//	tid	对象ID
func CreateUserChat(uid, tid uint) (*Chat, error) {
	if _default.DB == nil {
		return nil, xerror.New("数据库未连接")
	}
	// 创建聊天群
	chat := Chat{
		UserId:    uid,
		TypeId:    2,
		CreatedAt: time.Now().Format(time.DateTime),
	}
	err := _default.DB.Table(_default.ChatTable).Create(&chat).Error
	if err != nil {
		return nil, xlog.AE("聊天/群创建失败", err)
	}
	// 添加群成员uid
	chat_user := ChatUser{
		ChatId:    chat.Id,
		UserId:    uid,
		Nickname:  _default.GetUserNickname(tid),
		Thumb:     _default.GetUserAvatar(tid),
		CreatedAt: time.Now().Format(time.DateTime),
	}
	err = _default.DB.Table(_default.ChatUserTable).Create(&chat_user).Error
	if err != nil {
		return nil, xlog.AE("群成员加入失败", err)
	}
	// 添加群成员tid
	chat_user_t := ChatUser{
		ChatId:    chat.Id,
		UserId:    tid,
		Nickname:  _default.GetUserNickname(uid),
		Thumb:     _default.GetUserAvatar(uid),
		CreatedAt: time.Now().Format(time.DateTime),
	}
	err = _default.DB.Table(_default.ChatUserTable).Create(&chat_user_t).Error
	if err != nil {
		return nil, xlog.AE("群成员加入失败", err)
	}
	return &chat, nil
}
